package com.spzx.user.controller;

import com.spzx.common.core.web.controller.BaseController;
import com.spzx.common.core.web.domain.AjaxResult;
import com.spzx.common.redis.service.RedisService;
import com.spzx.user.service.ISmsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * ClassName: SmsController
 * Package: com.spzx.user.controller
 * Description:
 */
@Tag(name = "短信测试接口")
@RestController
@RequestMapping("/sms")
public class SmsController extends BaseController {

    @Autowired
    private RedisService redisService;

    @Autowired
    private ISmsService smsService;

    @Operation(summary = "获取短信验证码")
    @GetMapping("/sendCode/{phone}")
    public AjaxResult sendCode(@PathVariable("phone") String phone) {
        String regex = "^1[3-9]\\d{9}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(phone);
        if (!matcher.matches()) {
            throw new IllegalArgumentException("手机号不合法");
        }
        //生成验证码存入redis
        String code = new DecimalFormat("0000").format(new Random().nextInt(10000));
        redisService.setCacheObject("phone:code" + phone, code, 5L, TimeUnit.MINUTES);

        Map<String, Object> args = new HashMap<>();
        args.put("phone", phone);
        args.put("code", code);
        smsService.send(args);

        return success();
    }
}
